package com.ctrip.ec.api.admin.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Method;

/**
 * Created by cannon on 2018/3/26.
 */
public class JsonSerializer {

    private static final Logger logger = LoggerFactory.getLogger(JsonSerializer.class);
    static ObjectMapper mapper = new ObjectMapper();

    static void write(Object value, Method method, HttpServletResponse res) throws IOException {


        JsonBody meta = method.getAnnotation(JsonBody.class);
        JsonMapper jm = new JsonMapper(mapper);
        if (meta == null || meta.value() == true) {
//            ResultBody obj = new ResultBody(200, "Success", value);

            response(null, value, jm, res);
        }

    }

    private static void response(String callback, Object value, JsonMapper om, HttpServletResponse response) throws IOException {
        if (callback != null) {
            response.setContentType("application/javascript; charset=UTF-8");
            // call setContentType before getWriter(), or else UTF-8 doesn't work
            Writer writer = response.getWriter();
            writer.write(callback);
            writer.write('(');
            om.writeValue(writer, value);
            writer.write(')');
        } else {
            response.setContentType("application/json; charset=UTF-8");
            om.writeValue(response.getWriter(), value);
        }
    }

}